package com.jk.tweetsnear;

import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.User;
import twitter4j.auth.AccessToken;
import twitter4j.auth.RequestToken;
import twitter4j.conf.Configuration;
import twitter4j.conf.ConfigurationBuilder;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences.Editor;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Html;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

import com.google.analytics.tracking.android.GoogleAnalytics;
import com.google.analytics.tracking.android.Tracker;
import com.jk.tweetsnear.application.App;
import com.jk.tweetsnear.gps.GPSTracker;
import com.jk.tweetsnear.utils.AlertDialogManager;
import com.jk.tweetsnear.utils.ConnectionDetector;
import com.jk.tweetsnear.utils.Const;
import com.jk.tweetsnear.utils.Utils;

public class MainMenuActivity extends Activity
{

	public final String TAG = getClass().getSimpleName() + Utils.TAG_OPTION;

	private ConnectionDetector cd;
	private AlertDialogManager alert = new AlertDialogManager();
	private Tracker mGaTracker;
	private GoogleAnalytics mGaInstance;

	private static RequestToken requestToken; // 스태틱으로 할 것

	private Button btnConnTwitter;
	private Button btnMoveList;

	private ProgressDialog progDialog;
	private int exit = 0;

	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main_menu_activity);

		mGaInstance = GoogleAnalytics.getInstance(this);
		mGaTracker = mGaInstance.getTracker(Utils.TRACKER_ID); 

		App.sharedPreferences = getApplicationContext().getSharedPreferences("MyPref", 0);

		setWidjet();

		if (Utils.DEBUG)
			Log.i(Utils.FILLTER, TAG + " onCreate... ");				

		cd = new ConnectionDetector(getApplicationContext());
		if (cd.isConnectingToInternet() == false)
		{
			alert.showAlertDialog(MainMenuActivity.this, "Internet Connection Error", "Please connect to working Internet connection", false);
			return;
		}

		GPSTracker gps = new GPSTracker(this);
		if(gps != null)
		{	
			if (gps.canGetLocation() == false)
			{
				gps.showSettingsAlert(this);
			}
		}

		if (isTwitterLoggedInAlready() == false)
		{
			Uri uri = getIntent().getData();
			if (uri != null && uri.toString().startsWith(Const.CALLBACK_URL))
			{
				new AccessTwitter().execute(uri);
			}
		} else
		{
			// 이미 트위터 로그인
			btnConnTwitter.setText("WELCOME");
			btnMoveList.setEnabled(true);
			btnConnTwitter.setEnabled(false);
		}			
	}

	@Override
	public void onStart()
	{
		super.onStart();
		mGaTracker.sendView("/MainMenuActivity");
	}


	@Override
	protected void onNewIntent(Intent intent)
	{
		if (Utils.DEBUG)
			Log.i(Utils.FILLTER, TAG + " onNewIntent... ");	
		super.onNewIntent(intent);

		setIntent(intent);

		App.sharedPreferences = getApplicationContext().getSharedPreferences("MyPref", 0);

		if (isTwitterLoggedInAlready() == false)
		{
			Uri uri = getIntent().getData();
			if (uri != null && uri.toString().startsWith(Const.CALLBACK_URL))
			{
				new AccessTwitter().execute(uri);
			} else 
			{
				if (Utils.DEBUG)
					Log.i(Utils.FILLTER, TAG + " getIntent().getData() is null... ");					
			}
		} else
		{
			// 이미 트위터 로그인
			btnConnTwitter.setText("WELCOME");
			btnMoveList.setEnabled(true);
			btnConnTwitter.setEnabled(false);
		}			
	}

	@Override
	protected void onResume()
	{

		MainActivity.arrayTweetData.clear();

		if (Utils.DEBUG)
			Log.i(Utils.FILLTER, TAG + " onResume... ");		

		super.onResume();
	}

	public void setWidjet()
	{
		btnConnTwitter = (Button) findViewById(R.id.btn_connTwt);
		btnMoveList = (Button) findViewById(R.id.btn_moveList);

		if (isTwitterLoggedInAlready() == false)
			btnMoveList.setEnabled(false);
		else
			btnMoveList.setEnabled(true);

		btnConnTwitter.setOnClickListener(onClick);
		btnMoveList.setOnClickListener(onClick);
	}

	OnClickListener onClick = new OnClickListener()
	{

		@Override
		public void onClick(View v)
		{
			Intent intent  = new Intent(MainMenuActivity.this, MainActivity.class);

			switch (v.getId())
			{
			case R.id.btn_connTwt:
				mGaTracker.sendEvent("ui_action", "button_press", "twitter_login", 0L);

				loginToTwitter();
				break;
			case R.id.btn_moveList:
				mGaTracker.sendEvent("ui_action", "button_press", "move_list", 0L);

				intent.putExtra("tabMenu", "list");
				startActivity(intent);
				break;
			}
		}

	};

	private class AccessTwitter extends AsyncTask<Uri, String, Boolean>
	{
		@Override
		protected void onPreExecute()
		{
			super.onPreExecute();
			if (progDialog == null)
			{
				progDialog = new ProgressDialog(MainMenuActivity.this);
			}
			progDialog.setMessage("Access to twitter...");
			progDialog.setIndeterminate(false);
			progDialog.setCancelable(false);
			progDialog.show();
		}

		@Override
		protected Boolean doInBackground(Uri... params)
		{
			Uri uri = params[0];
			if (uri != null && uri.toString().startsWith(Const.CALLBACK_URL))
			{
				String verifier = uri.getQueryParameter(Const.URL_TWITTER_OAUTH_VERIFIER);
				try
				{
					AccessToken accessToken = null;
					if(requestToken != null)
					{
						accessToken = App.twitter.getOAuthAccessToken(requestToken, verifier);
					} else
					{
						if (Utils.DEBUG)
							Log.e(Utils.FILLTER, TAG + "requestToken is null... ");
					}


					// Shared Preferences
					Editor e = App.sharedPreferences.edit();
					e.putString(Const.PREF_KEY_OAUTH_TOKEN, accessToken.getToken());
					e.putString(Const.PREF_KEY_OAUTH_SECRET, accessToken.getTokenSecret());
					e.putBoolean(Const.PREF_KEY_TWITTER_LOGIN, true);
					e.commit();

					if (Utils.DEBUG)
						Log.e(Utils.FILLTER, TAG + " accessToken = " + accessToken.getToken());

					long userID = accessToken.getUserId();
					User user = App.twitter.showUser(userID);
					String username = user.getName();

					if (Utils.DEBUG)
					{
						Log.e(Utils.FILLTER, TAG + " userID = " + userID + " " + username);
						Log.v(Utils.FILLTER, TAG + " Thanks = " + Html.fromHtml("<b>Welcome " + username + "</b>"));
					}

					return true;
				} catch (Exception e)
				{
					e.printStackTrace();
				}
			}
			return false;
		}

		@Override
		protected void onPostExecute(Boolean result)
		{
			progDialog.dismiss();
			if (result)
			{
				// 트위터 로그인 되었을 때
				btnConnTwitter.setText("WELCOME");
				btnMoveList.setEnabled(true);
				btnConnTwitter.setEnabled(false);
			} else
			{
				if (Utils.DEBUG)
					Log.e(Utils.FILLTER, TAG + " accessToken error");
			}
			super.onPostExecute(result);
		}
	}

	private class RequestTwitter extends AsyncTask<String, String, String>
	{
		@Override
		protected void onPreExecute()
		{
			super.onPreExecute();
			if (progDialog == null)
			{
				progDialog = new ProgressDialog(MainMenuActivity.this);
			}
			progDialog.setMessage("Login to twitter...");
			progDialog.setIndeterminate(false);
			progDialog.setCancelable(false);
			progDialog.show();
		}

		@Override
		protected String doInBackground(String... params)
		{
			try
			{
				requestToken = App.twitter.getOAuthRequestToken(Const.CALLBACK_URL);
			} catch (TwitterException e)
			{
				e.printStackTrace();
			}
			return null;
		}

		@Override
		protected void onPostExecute(String result)
		{
			progDialog.dismiss();

			if (requestToken != null)
			{
				Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(requestToken.getAuthenticationURL()));
				intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
				intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
				MainMenuActivity.this.startActivity(intent);

			} else
			{
				if (Utils.DEBUG)
					Log.e(Utils.FILLTER, TAG + " requstToken error");
			}
			super.onPostExecute(result);
		}
	}

	private void loginToTwitter()
	{
		if (isTwitterLoggedInAlready() == false)
		{
			ConfigurationBuilder builder = new ConfigurationBuilder();
			builder.setOAuthConsumerKey(Const.CONSUMER_KEY);
			builder.setOAuthConsumerSecret(Const.CONSUMER_SECRET);
			Configuration configuration = builder.build();

			TwitterFactory factory = new TwitterFactory(configuration);
			App.twitter = factory.getInstance();

			new RequestTwitter().execute();
		} else
		{
			Toast.makeText(getApplicationContext(), "Already Logged into twitter", Toast.LENGTH_LONG).show();
		}
	}

	private boolean isTwitterLoggedInAlready()
	{
		return App.sharedPreferences.getBoolean(Const.PREF_KEY_TWITTER_LOGIN, false);
	}

	class updateTwitterStatus extends AsyncTask<String, String, String>
	{
		@Override
		protected void onPreExecute()
		{
			super.onPreExecute();
			if (progDialog == null)
			{
				progDialog = new ProgressDialog(MainMenuActivity.this);
			}

			progDialog.setMessage("Updating to twitter...");
			progDialog.setIndeterminate(false);
			progDialog.setCancelable(false);
			progDialog.show();
		}

		protected String doInBackground(String... args)
		{
			String status = args[0];
			try
			{
				ConfigurationBuilder builder = new ConfigurationBuilder();
				builder.setOAuthConsumerKey(Const.CONSUMER_KEY);
				builder.setOAuthConsumerSecret(Const.CONSUMER_SECRET);
				String access_token = App.sharedPreferences.getString(Const.PREF_KEY_OAUTH_TOKEN, "");
				String access_token_secret = App.sharedPreferences.getString(Const.PREF_KEY_OAUTH_SECRET, "");

				AccessToken accessToken = new AccessToken(access_token, access_token_secret);
				App.twitter = new TwitterFactory(builder.build()).getInstance(accessToken);

				twitter4j.Status response = App.twitter.updateStatus(status);

			} catch (TwitterException e)
			{
				e.printStackTrace();
			}
			return null;
		}

		protected void onPostExecute(String file_url)
		{
			progDialog.dismiss();
			runOnUiThread(new Runnable()
			{
				@Override
				public void run()
				{
					Toast.makeText(getApplicationContext(), "Status tweeted successfully", Toast.LENGTH_SHORT).show();
				}
			});

			super.onPostExecute(file_url);
		}
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event)
	{
		
		switch (keyCode)
		{
		case KeyEvent.KEYCODE_BACK:
			if(Utils.isRecommend(MainMenuActivity.this) == false)
			{
				if(exit == 1)
					finish();
				else
					Utils.showAlert(MainMenuActivity.this, "Rating this app, Thank you.");
				exit = 1;
			} else
				finish();
			break;
		}

		return false;

	}


}
